<!-- 员工管理新建 -->
<template>
    <div>
        <el-breadcrumb separator="/" class="bread-title">
            <el-breadcrumb-item :to="{ path: '/staffmanage' }">员工管理</el-breadcrumb-item>
            <el-breadcrumb-item v-if="pageType==='add'">新增</el-breadcrumb-item>
            <el-breadcrumb-item v-if="pageType==='edit'">编辑</el-breadcrumb-item>
        </el-breadcrumb>

        <el-form :model="ruleForm" :rules="rules" ref="ruleform" label-width="140px" class="demo-ruleForm">
            <el-form-item label="姓名：" prop="name" >
                <el-input v-model="ruleForm.name" placeholder="请输入姓名" maxlength="20" show-word-limit style="width: 300px;"></el-input>
            </el-form-item>
            <el-form-item label="EHR岗位：" prop="post" required>
                <span>{{ruleForm.ehrJobName}}</span>
            </el-form-item>
            <el-form-item label="岗位：" prop="post">
                <el-select v-model="ruleForm.post" @change="postChange" filterable style="width: 300px;">
                    <el-option v-for="item in postlist"
                               :key="item.id"
                               :label="item.label"
                               :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="业务线:" prop="line">
                <span>{{ruleForm.line}}</span>
            </el-form-item>
            <el-form-item label="部门:" prop="depart">
                <span>{{ruleForm.depart}}</span>
            </el-form-item>
            <el-form-item label="角色:" prop="role">
                <span>{{ruleForm.role}}</span>
            </el-form-item>
            <el-form-item label="工号:" prop="jobnumber">
                <el-input type="text" placeholder="请输入工号" v-model="ruleForm.jobnumber" style="width:300px"></el-input>
            </el-form-item>
            <el-form-item label="入职时间:" prop="startime">
                <el-date-picker
                        v-model="ruleForm.startime"
                        type="date"
                        placeholder="选择日期"
                        style="width:300px"
                        :picker-options="pickerOptions0"
                        @change="changeDate0"
                >
                </el-date-picker>
            </el-form-item>
            <el-form-item class="starmark" label="离职时间:" prop="endtime">
                <el-date-picker
                        v-model="ruleForm.endtime"
                        type="date"
                        placeholder="选择日期"
                        style="width:300px"
                        @change="getSTime"
                        :picker-options="pickerOptions1"
                >
                </el-date-picker>
                <el-radio-group v-model="ruleForm.tonow" @change="sourceFilter">
                    <el-radio label="至今"></el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="工作区域：" prop="regionId">
                <el-select v-model="ruleForm.regionId" filterable style="width:300px" @change="selectArea">
                    <el-option v-for="item in regionlist"
                               :key="item.id"
                               :label="item.name"
                               :value="item.id">
                    </el-option>               
                </el-select>
            </el-form-item>
            <el-form-item label="城市：" prop="cityId">
                <el-select v-model="ruleForm.cityId" filterable style="width:300px">
                    <el-option v-for="item in citylist"
                               :key="item.cityId"
                               :label="item.city"
                               :value="item.cityId">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button style="margin-left: 100px;" type="primary" @click="savehander('ruleform')">保存</el-button>
                <el-button type="primary" @click="backhander">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
    import api from '@/api/apiPath'

    export default {
        data() {
            var checkjobnumber = (rule, value, callback) => {
                let reg =/^[0-9a-zA-Z]*$/g;
                if (!reg.test(value)) {
                    callback(new Error('只能输入英文字母和数字'));
                } else {
                    callback();
                }
            }
            return {
                //入职时间<离职时间
                pickerOptions0: {
                    disabledDate: (time) => {
                        if (this.ruleForm.endtime) {
                            return time.getTime() > this.ruleForm.endtime;
                        }else {
                            return time.getTime() > Date.now()
                        }
                    }
                },
                pickerOptions1: {
                    disabledDate: (time) => {
                        return time.getTime() < this.ruleForm.startime 
                    }
                },
                citylist: [],
                citylistMap: {},
                pageType: undefined,
                postlist: [],
                postlistMap: {},
                regionlist:[],
                ruleForm: {
                    cityId: undefined,
                    name: undefined,
                    post: '',
                    startime: '',
                    endtime: '',
                    role: '未选择',
                    tonow: '',//至今
                    line: '未选择',//业务线
                    depart: '未选择',//部门
                    jobnumber: '',//工号
                    regionId:'',//工作区域
                    ehrJobName:'',//ehr岗位
                },
                rules: {
                    name: [
                        {required: true, message: '请输入姓名', trigger: 'blur'}
                    ],
                    post:[
                        {required: true, message: '请选择岗位', trigger: 'blur'}
                    ],
                    value: [
                        {required: true, message: '请选择岗位', trigger: 'blur'}
                    ],
                    jobnumber: [
                        {required: true, message: '请输入工号', trigger: 'blur'},
                        {validator: checkjobnumber, trigger: 'blur'}
                    ],
                    startime: [
                        {required: true, message: '请选择入职时间', trigger: 'blur'}
                    ],
                    cityId: [
                        {required: true, message: '请选择工作城市', trigger: 'blur'}
                    ],
                    regionId: [
                         {required: true, message: '请选择工作区域', trigger: 'blur'}
                    ]
                },
            }
        },
        methods: {
            //选择区域级联城市
            selectArea(){
                this.ruleForm.cityId = ''
                this.getareacity()
            },
            getareacity(){                
                this.$axios.post('/city/region/getCity/byRegion',{regionId:this.ruleForm.regionId}).then(res=>{
                    this.citylist = res
                })
            },
            savehander(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.submitRequest(this.ruleForm)
                    }
                });
            },
            backhander() {
                this.$router.push({path: '/staffmanage'})
            },
            handleChange(value) {
                this.ruleForm.line = value[1]
                this.ruleForm.depart = value[2]
            },
            getSTime(value) {
                this.ruleForm.endtime = value ? new Date(value).getTime() : ''
                this.ruleForm.tonow = ''
            },
            sourceFilter(value) {
                this.ruleForm.endtime = ''
                this.ruleForm.tonow = "至今"
            },
            changeDate0(value) {
                this.ruleForm.startime = value ? new Date(value).getTime() : undefined
            },
            submitRequest(params) {
                let url = api.addStaff;
                if (this.pageType === 'edit') {
                    url = api.editStaff;
                }
                if (this.ruleForm.tonow == '' && !this.ruleForm.endtime) {
                    this.$message({
                        message: '请选择离职时间',
                        type: 'warning'
                    });
                    return
                }
                let currentcity = this.citylist.find(val=>{
                   return val.cityId == this.ruleForm.cityId
                })
                let obj = {}
                obj.id = this.$route.query.id
                obj.staffName = params.name,
                obj.staffCode = params.jobnumber,
                obj.stationId = params.post
                obj.cityId = currentcity.cityId
                obj.cityName = currentcity.city
                // obj.cityId = params.cityId
                // obj.cityName = this.citylistMap[params.cityId]
                obj.hiredate = this.$format.dateFormat(params.startime, true, '-')
                if (!params.endtime == '') {
                    obj.leavedate =  params.tonow === "至今" ? "" : this.$format.dateFormat(params.endtime, true, '-')
                }else {
                     obj.leavedate = ''
                }
                obj.hithertoMark =  params.tonow === "至今" ? 1 : 0
                this.axios.post(url, obj).then((res) => {
                    if (res) {
                        this.$message({
                            message: this.pageType === 'edit' ? "修改成功" : "新增成功",
                            type: 'success'
                        });
                        this.$router.push({path: '/staffmanage'})
                    }
                })
            },
            postChange(id) {
                let item = this.postlistMap[id];
                this.ruleForm.line = item.businessLineName;
                this.ruleForm.depart = item.departmentName;
                this.ruleForm.role = item.roleName;
            },
            getAllPostList() {
                this.axios.post(api.getAllPostList, {}).then((res) => {
                    let postlist = [];
                    let postlistMap = {};
                    res.data.data.forEach((item) => {
                        postlist.push({
                            id: item.stationId,
                            label: `${item.stationName}-${item.businessLineName}-${item.departmentName}`
                        })
                        postlistMap[item.stationId] = item;
                    })
                    this.postlist = postlist;
                    this.postlistMap = postlistMap;
                    // 岗位拿到之后再 获取  便于渲染业务线 部门 角色
                    if (this.pageType === 'edit') {
                        this.getSingleStaffById(this.$route.query.id)
                    }
                })
            },
            // getAllCityList() {
            //     this.axios.post(api.getAllCityList, {}).then((res) => {
            //         this.citylist = res.data.data.cityList;
            //         let citylistMap = {};
            //         this.citylist.forEach((item) => {
            //             citylistMap[item.cityId] = item.city
            //         })
            //         this.citylistMap = citylistMap;
            //     })
            // },
            getSingleStaffById(id) {
                this.axios.post(api.getSingleStaffById, {
                    id: id
                }).then((res) => {
                    let params = res.data.data;
                    this.ruleForm = {
                        cityId: params.cityId,
                        name: params.staffName,
                        post: params.stationId,
                        startime: params.hiredate,
                        endtime: params.leavedate,
                        role: '未选择',
                        tonow: params.hithertoMark === 1 ? "至今" : "",//至今
                        line: '未选择',//业务线
                        depart: '未选择',//部门
                        jobnumber: params.staffCode,//工号
                        regionId : params.regionId,//区域
                        ehrJobName: params.ehrJobName
                    }
                    this.postChange(params.stationId);
                    this.getareacity();
                })
            },
            getarealist(){
                this.axios.get(api.CITYREGIONALL).then(res=>{
                    this.regionlist = [];
                    let temparr =  res.data.data
                    temparr.forEach(item=>{
                        if ( item.name.indexOf('海外') == -1) {
                            this.regionlist.push(item)
                        }
                    })
                })
            }
        },
        created() {
            this.pageType = this.$route.query.type;
            this.getAllPostList();
            // this.getAllCityList();
            this.getarealist();
        }
    }
</script>

<style lang="stylus">
    .starmark > .el-form-item__label:before{
        content:"*"
        color:red;
        margin-right: 2px;
    }
</style>